package com.sjtu.rest;

import com.sjtu.dao.model.ClientInfo;
import com.sjtu.dao.repository.ClientInfoRepository;
import com.sjtu.feign.ClientInfoFeign;
import com.sjtu.util.JpaUtil;
import com.sjtu.web.BaseRest;
import com.sjtu.web.Result;
import com.sjtu.web.form.ClientInfoForm;
import com.sjtu.web.search.ClientInfoSearch;
import com.sjtu.web.vo.ClientInfoVo;
import com.sjtu.zookeeper.InstanceDetails;
import com.sjtu.zookeeper.ServiceDiscoverUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.curator.x.discovery.ServiceProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * nerine
 * 1/28/2020
 */
@Slf4j
@RequestMapping(ClientInfoFeign.PREFIX)
@RestController
public class ClientInfoRest extends BaseRest {
    @Autowired
    private ClientInfoRepository repository;

    @PostMapping("/list")
    public Result<?> list(@RequestBody ClientInfoSearch search) {
        ClientInfo ex = new ClientInfo();
        if(StringUtils.isNotBlank(search.getSystemId())) {
            ex.setSystemId(search.getSystemId());
        }
        Page<ClientInfo> result = repository.findAll(
                Example.of(ex),
                PageRequest.of(search.getCurrent(), search.getSize(), Sort.by(Sort.Direction.DESC, "createdDate"))
        );
        List<ClientInfoVo> voList = result.stream()
                .map(e -> createTaskInfoVo(e)).collect(Collectors.toList());
        return success(voList);
    }

    @PostMapping("/save")
    public Result<?> save(@RequestBody ClientInfoForm form) {
        ClientInfo clientInfo = new ClientInfo();
        clientInfo.setSystemId(form.getSystemId());
        clientInfo = repository.findOne(Example.of(clientInfo)).orElse(new ClientInfo());

        clientInfo.setSystemId(form.getSystemId());
        clientInfo.setSystemName(form.getSystemName());

        JpaUtil.setModifyInfo(form.getOperatorId(), clientInfo);

        return success(repository.save(clientInfo));
    }
    @GetMapping("/detail/{id}")
    public Result<ClientInfoVo> detail(@PathVariable String id) {
        ClientInfo info = repository.findById(id).get();
        return success(createTaskInfoVo(info));
    }

    private ClientInfoVo createTaskInfoVo(ClientInfo e) {
        ClientInfoVo vo = new ClientInfoVo();
        vo.setSystemName(e.getSystemName());
        vo.setSystemId(e.getSystemId());
        vo.setIdClientInfo(e.getIdClientInfo());
        vo.setInstances(e.getInstances());
        vo.setCreatedDate(e.getCreatedDate());
        if(e.getInstances() == null) {
            ServiceProvider<InstanceDetails> provider = ServiceDiscoverUtil.getServiceProvider(e.getSystemId());
            try {
                List<String> ipList = provider.getAllInstances()
                        .stream().map(f -> f.getAddress() + ":" + f.getPort())
                        .collect(Collectors.toList());
                vo.setInstances(String.join(",", ipList));
            } catch (Exception ex) {
                log.error("get instance info error: ", e);
            }
        }

        return vo;
    }
}
